//
//  WH_RechargeViewController.m
//  App_6.23
//
//  Created by wanghao on 16/8/2.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_RechargeViewController.h"
#import "WH_ListOrder.h"
@interface WH_RechargeViewController ()<PayPalPaymentDelegate>
@property (weak, nonatomic) IBOutlet UITextField *totalTF;
@property (nonatomic, strong) PayPalConfiguration *payPalConfig;
@property (nonatomic, strong) NSDictionary *dataDic;
@property (nonatomic, strong) WH_ListOrder *list;

@end

@implementation WH_RechargeViewController
-(void)viewWillAppear:(BOOL)animated{
    
    
    [self.tabBarController.tabBar setHidden:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    
    
    [self.tabBarController.tabBar setHidden:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [PayPalMobile preconnectWithEnvironment:PayPalEnvironmentSandbox];
    [self createPayPal];
    
}
#pragma mark - PayPal

-(void)createPayPal{
    
    _payPalConfig = [[PayPalConfiguration alloc] init];
    //是否接受信用卡
    _payPalConfig.acceptCreditCards = YES;
    
    //商家名称
    _payPalConfig.merchantName = @"HZL";
    //paypal账号下的地址信息
    _payPalConfig.payPalShippingAddressOption = PayPalShippingAddressOptionNone;
    
    //配置语言环境
    _payPalConfig.languageOrLocale = [NSLocale preferredLanguages][0];
    NSLog(@"PayPal iOS SDK version: %@", [PayPalMobile libraryVersion]);
    
    
}
#pragma mark - paypal支付

-(void)CreatePayment{
    
    PayPalPayment *payment = [[PayPalPayment alloc] init];
    
    //订单总额
    payment.amount = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@",_totalTF.text]];
    
    //货币类型-RMB是没用的
    payment.currencyCode = @"USD";
    
    //订单描述
    payment.shortDescription = @"充值";
    
    //生成paypal控制器，并模态出来(push也行)
    //将之前生成的订单信息和paypal配置传进来，并设置订单VC为代理
    PayPalPaymentViewController *paymentViewController = [[PayPalPaymentViewController alloc] initWithPayment:payment                                                                                           configuration:self.payPalConfig                                                                                          delegate:self];
    
    //模态展示
    [self presentViewController:paymentViewController animated:YES completion:nil];
    
    
}
//订单支付完成后回调此方法
- (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
    NSLog(@"PayPal Payment Success!");
    
    [self postRecharge:_list.pay_id payKey:_list.pay_key total:_totalTF.text payCode:completedPayment.confirmation];
    
    [self postPAYPAL:completedPayment.confirmation];
    NSLog(@"%@", completedPayment.confirmation);

}
-(void)postTatolRecharge:(NSString *)orderPrice {
    
    NSString *body = [NSString stringWithFormat:@"action=payment&user_id=%@&cart_total=%@&allpayment=0", NSUSERID,orderPrice];
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        NSString *message = [dic objectForKey:@"message"];
        NSDictionary *payment_array = [dic objectForKey:@"payment_array"];
        NSDictionary *PAYPALDic = [payment_array objectForKey:@"PAYPAL"];
         self.list = [WH_ListOrder modelWithDictionary:PAYPALDic];
        if ([status isEqualToString:@"success"]) {
            
            [self CreatePayment];
            
        }else{
            
            [WSProgressHUD showImage:nil status:message];
            
        }
        
    } failure:^(NSError *error) {
        
        
    }];
    
}
- (void)postPAYPAL:(NSDictionary *)dic{
    
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    
    [para setObject:@"PAYPAL" forKey:@"action"];
    [WH_AppTools postUrl:URLstr body:para result:HXJSON requestStyle:HXRequestDic headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        NSString *message = [dic objectForKey:@"message"];
        if ([status isEqualToString:@"success"]) {
            
            [WSProgressHUD showImage:nil status:status maskType:WSProgressHUDMaskTypeClear];
            
        }else{
            
            [WSProgressHUD showImage:nil status:message maskType:WSProgressHUDMaskTypeClear];
        }
        
    } failure:^(NSError *error) {
        
        
    }];
    

    
}

#pragma mark - 充值 POST

- (void)postRecharge:(NSString *)payID payKey:(NSString *)key total:(NSString *)total payCode:(NSDictionary *)payCode{
    
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    
    [para setObject:@"checkout_recharge" forKey:@"action"];
    [para setObject:NSUSERID forKey:@"user_id"];
    [para setObject:key forKey:@"pay_key"];
    [para setObject:payID forKey:@"pay_id"];
    [para setObject:total forKey:@"total"];
    [para setObject:payCode forKey:@"pay_code"];

    [WH_AppTools postUrl:URLstr body:para result:HXJSON requestStyle:HXRequestDic headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        NSString *message = [dic objectForKey:@"message"];
        if ([status isEqualToString:@"success"]) {
            
            [WSProgressHUD showImage:nil status:status maskType:WSProgressHUDMaskTypeClear];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self dismissViewControllerAnimated:YES completion:^{
                    
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }];
            });


        }else{
            
            [WSProgressHUD showImage:nil status:message maskType:WSProgressHUDMaskTypeClear];
        }
        
    } failure:^(NSError *error) {
        
        
    }];
    
    
}

//用户取消支付回调此方法
- (void)payPalPaymentDidCancel:(PayPalPaymentViewController *)paymentViewController {
    NSLog(@"PayPal Payment Canceled");
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

- (IBAction)oneBtn:(UIButton *)sender {
    
    _totalTF.text = @"10";
    
}

- (IBAction)twoBtn:(UIButton *)sender {
    
    _totalTF.text = @"20";

}
- (IBAction)fiveBtn:(UIButton *)sender {
    _totalTF.text = @"50";

}
- (IBAction)oneHBtn:(UIButton *)sender {
    _totalTF.text = @"100";

}
- (IBAction)twoHBtn:(UIButton *)sender {
    _totalTF.text = @"200";

}
- (IBAction)fiveHBtn:(UIButton *)sender {
    _totalTF.text = @"500";

}
- (IBAction)totalBtn:(UIButton *)sender {
    
    if (_totalTF.text.length == 0) {
        
        [WSProgressHUD showImage:nil status:@"请选择金额" maskType:WSProgressHUDMaskTypeClear];
    }else{
        
        [self postTatolRecharge:_totalTF.text];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
